iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
佛心分享-刷題不只是刷題

刷經典 LeetCode 題目系列 第 12

經典LeetCode 104. Maximum Depth of Binary Tree

  • 分享至 

  • xImage
  •  

給定一個二元樹,找出其最大深度。
二元樹的最大深度是從根節點到最遠葉節點的最長路徑上的節點數。

範例:

輸入: 二元樹 [3,9,20,null,null,15,7]
       3
      / \
     9  20
       /  \
      15   7
輸出: 3

解題思路

這道題要求找到二元樹的最大深度,這個問題可以透過遞迴法或者深度優先搜尋(DFS)或者廣度優先搜尋(BFS)來解。

廣度優先搜尋 BFS 版本的話,就是每遍歷完一層的所有節點後,深度就加1。

實作:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr)
            return 0;

        queue<TreeNode*> q;
        q.push(root);

        int depth = 0;
        // BFS
        while (!q.empty()) {
            int count = q.size(); // 當前這層的節點數量

            // 處理當前這層的所有節點
            for (int i = 0; i < count; i++) {
                TreeNode* node = q.front();
                q.pop();

                if (node->left != nullptr) {
                    q.push(node->left);
                }

                if (node->right != nullptr) {
                    q.push(node->right);
                }
            }
            depth++;
        }
        return depth;
    }
};

上一篇
經典LeetCode 190. Reverse Bits
系列文
刷經典 LeetCode 題目12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言